import flixel.util.FlxSave;
import flixel.util.FlxPoint;
import flixel.FlxG;

/**
* Handy, pre-built Registry class that can be used to store 
* references to objects and other things for quick-access. Feel
* free to simply ignore it or change it in any way you like.
*/
class Reg
{
	public static var levelName: String;	// nombre del archivo de nivel actual
	public static var entryPointId: Int;	// id del punto de guardado actual
	private static var _currentSaveSlot: String;
	private static var _items: Map<String, Int>;

	public static function load()
	{
		levelName = _save.data.levelName;
		entryPointId = _save.data.entryPointId;
		_items = new Map<String, Int>();
		// carga los items parseando la cadena
		var strItems: String = _save.data.items;
		strItems = strItems.substr(1, strItems.length - 2); // quita los {}
		for( i in strItems.split(", "))
		{
			var keyValue = i.split(" => ");
			_items[keyValue[0]] = Std.parseInt(keyValue[1]);
			//trace("load Item: \""+keyValue[0]+"\" - \""+keyValue[1]+"\"");
		}
	}

	public static function save()
	{
		trace("Saving data to slot: \""+_currentSaveSlot+"\"");
		_save.data.levelName = levelName;
		_save.data.entryPointId = entryPointId;
		_save.data.items = _items.toString();
		_save.data.timestamp = Date.now();
		_save.flush();
		trace("MAP: "+_save.data.items);
	} 

	private static var _save: FlxSave;

	public static function slotLoadDefault()
	{
		trace("Loading default data on slot: \""+_currentSaveSlot+"\"");
		levelName = "level0.tmx";
		entryPointId = 0;
		_items = new Map<String, Int>();
		save();
	}

	public static function slotWipeData()
	{
		trace("Wiping data from slot: \""+_currentSaveSlot+"\"");
		_save.erase();
	}

	public static function useSaveSlot(Slot: String)
	{
		_currentSaveSlot = Slot;
		var success = _save.bind(_currentSaveSlot);
		//trace("Binding slot: \""+_currentSaveSlot+"\"... "+(success?"OK!":"Failed."));
	}

	public static function slotHasData()
	{
		var hasData = _save.data.timestamp != null;
		//trace("Cheking if slot has data: \"" + hasData);
		return hasData;
	}

	public static function setItem(Item: String, Value: Int = 1)
	{
		_items[Item] = Value;
	}

	public static function hasItem(Item: String): Bool
	{
		var success = _items[Item] != null;
		trace("Asking for item: \""+Item+"\": "+success);
		return success;
	}

	public static function init()
	{
		_save = new FlxSave();
	}
}